﻿using System;

using AopAlliance.Intercept;
using Common.Logging;

namespace efish.Framework.Aop
{
    /// <summary>
    /// Basic implementation of a logging aspect using Common.Logging library.
    /// </summary>
    /// <author>Bruno Baia</author>
    /// <version>$Id: CommonLoggingAroundAdvice.cs,v 1.2 2007/06/27 16:10:59 bbaia Exp $</version>
    public class CommonLoggingAdvice : IMethodInterceptor
    {
        #region Logging
        private static readonly ILog LOG = LogManager.GetLogger(typeof(CommonLoggingAdvice));

        #endregion

        #region Fields

        private LogLevel _level = LogLevel.All;

        #endregion

        #region Properties

        public LogLevel Level
        {
            get { return _level; }
            set { _level = value; }
        }

        #endregion

        #region IMethodInterceptor Members

        public object Invoke(IMethodInvocation invocation)
        {
            Log("Intercepted call : about to invoke method '{0}'", invocation.Method.Name);
            object returnValue = invocation.Proceed();
            Log("Intercepted call : returned '{0}'", returnValue);
            return returnValue;
        }

        #endregion

        #region Private Methods

        private void Log(string text, params object[] args)
        {
            switch (Level)
            {
                case LogLevel.All:
                case LogLevel.Debug:
                    if (LOG.IsDebugEnabled) LOG.Debug(String.Format(text, args));
                    break;
                case LogLevel.Error:
                    if (LOG.IsErrorEnabled) LOG.Error(String.Format(text, args));
                    break;
                case LogLevel.Fatal:
                    if (LOG.IsFatalEnabled) LOG.Fatal(String.Format(text, args));
                    break;
                case LogLevel.Info:
                    if (LOG.IsInfoEnabled) LOG.Info(String.Format(text, args));
                    break;
                case LogLevel.Warn:
                    if (LOG.IsWarnEnabled) LOG.Warn(String.Format(text, args));
                    break;
                case LogLevel.Off:
                default:
                    break;
            }
        }

        #endregion
    }
}